<template>
  <div class="container">
    <a-spin :loading="spinLoading" :tip="spinTip" dot style="width: 100%;">
      <a-card class="custom-card" title="">
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="query"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
              label-align="left"
            >
              <a-row :gutter="16">
                <a-col :span="8">
                  <a-input-group>
                    <a-select v-model="query.keyword_type" placeholder="请选择" :style="{width:'120px'}">
                      <a-option value="name">名称</a-option>
                    </a-select>
                    <a-input v-model="query.name" placeholder="请输入名称" allow-clear />
                  </a-input-group>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="类型" field="">
                    <a-select v-model="query.type" placeholder="" allow-clear>
                      <a-option value="1" label="类型1" />
                      <a-option value="2" label="类型2" />
                      <a-option value="3" label="类型3" />
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="状态" field="">
                    <a-select v-model="query.status" :options="statusOptions" placeholder="全部"/>
                  </a-form-item>
                </a-col>
                <a-col :span="12" :style="{'margin-bottom': '20px'}">
                  <a-input-group>
                    <a-select v-model="query.time_type" placeholder="时间类型" :style="{width:'120px'}">
                      <a-option value="created_at" label="添加时间" />
                      <a-option value="updated_at" label="修改时间" />
                    </a-select>
                    <a-range-picker v-model="query.date_value" allow-clear style="width: 100%"/>
                  </a-input-group>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <a-divider style="height: 84px" direction="vertical" />
          <a-col :flex="'86px'" style="text-align: right">
            <a-space direction="vertical" :size="18">
              <a-button type="primary" @click="search()">
                <template #icon><icon-search /></template>搜索
              </a-button>
              <a-button status="success" @click="refresh()">
                <template #icon><icon-refresh /></template>重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
        <a-divider style="margin-top: 0" />
        <a-row style="margin-bottom: 16px">
          <a-col :span="16">
            <a-space>
              <a-checkbox @change="customSelectAll">
                <template #checkbox="{ checked }">
                  <a-space
                    align="start"
                    class="custom-checkbox-card"
                    :class="{ 'custom-checkbox-card-checked': checked }"
                  >
                    <div className="custom-checkbox-card-mask">
                      <div className="custom-checkbox-card-mask-dot" />
                    </div>
                    <div>
                      <div className="custom-checkbox-card-title">全选</div>
                    </div>
                  </a-space>
                </template>
              </a-checkbox>
              <a-button type="primary" status="warning" @click="batchSelect('hide')">批量操作</a-button>
              <a-button type="primary" status="danger" @click="batchDel()">
                <template #icon><icon-delete /></template>批量删除
              </a-button>
              <a-button status="warning" @click="doExport()">
                <template #icon><icon-download /></template>下载
              </a-button>
              <a-upload action="">
                <template #upload-button>
                  <a-button>
                    <template #icon><icon-upload /></template>导入
                  </a-button>
                </template>
              </a-upload>
              <a-button type="primary" @click="add()">
                <template #icon><icon-plus /></template>
                <template #default>添加</template>
              </a-button>
            </a-space>
          </a-col>
          <a-col :span="8" style="text-align: right">
            <a-button-group>
              <a-button @click="refresh()"><template #icon><icon-sync /></template></a-button>
              <a-dropdown position="br" :popup-max-height="false">
                <a-button>
                  列配置 <icon-select-all />
                </a-button>
                <template #content>
                  <a-doption v-for="(fruit, index) in allTableThead" :key="fruit">
                    <a-checkbox-group v-model="defaultTableThead" @change="handleTableThead">
                      <a-checkbox :value="allTableThead[index]">{{ tableTheadOptions[fruit].label }}</a-checkbox>
                    </a-checkbox-group>
                  </a-doption>
                </template>
              </a-dropdown>
            </a-button-group>
          </a-col>
        </a-row>
        <a-table
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :pagination="false"
          :columns="columns"
          :data="renderData"
          :bordered="{ wrapper: true, cell: true }"
          :row-selection="rowSelection"
          column-resizable
          @select="select"
          @selection-change="selectionChange"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
          @sorter-change="sorting"
        >
          <template #status="{ record }">
            <span v-if="record.status === '1'" class="circle"></span>
            <span v-else class="circle pass"></span>
            状态名
          </template>
          <template #operations="{ record }">
            <a-space>
              <a-button v-permission="['admin']" type="text" size="small">查看</a-button>
              <a-button type="primary" size="small" @click="add(record)"><template #icon><icon-edit /></template>编辑</a-button>
              <a-popconfirm content="确定要删除这条数据吗？" type="warning" position="br" @ok="del([record])">
                <a-button type="primary" status="danger" size="small"><template #icon><icon-delete /></template>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>
        <pagination-manage
          v-show="pagination.total > 0"
          :total="pagination.total"
          :current="pagination.current"
          :page-size="pagination.pageSize"
          @pageCBK="onPageChange"
          @pageSizeCBK="onPageSizeChange"
        />
      </a-card>
    </a-spin>

    <Detail
      ref="detailRef"
      @saveCallback="fetchData"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, h, compile, getCurrentInstance } from 'vue';
  import { useI18n } from 'vue-i18n';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import { Message, Modal } from '@arco-design/web-vue';

  import useLoading from '@/hooks/loading';
  import { exportExcel } from '@/utils';
  import { DataState, QueryParams, apiList, apiDel, apiExport } from '@/api/test';
  import PaginationManage from '@/components/pagination/index.vue';
  import Detail from './components/detail.vue';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const { proxy } = getCurrentInstance() as any;
  const baseQuery = () => {
    return {
      page: 1,
      limit: 20,
      keyword_type: 'name',
      name: '',
      type: '1', // 不能用数字
      time_type: 'created_at',
      date_value: [],
      status: '',
    };
  };
  const baseColumns = () => {
    return [
      {
        title: 'ID', dataIndex: 'id',
        align: 'center' as 'left' | 'right' | 'center',
        fixed: 'left' as 'left' | 'right',
        sortable: {sortDirections: ['ascend', 'descend'] as ('ascend' | 'descend')[]},
      },
      {
        title: '名称', dataIndex: 'name',
        align: 'center' as 'left' | 'right' | 'center',
      },
      {
        title: '创建时间', dataIndex: 'created_at',
        align: 'center' as 'left' | 'right' | 'center',
        sortable: {sortDirections: ['ascend', 'descend'] as ('ascend' | 'descend')[]},
      },
      {
        title: '状态', dataIndex: 'status',
        align: 'center' as 'left' | 'right' | 'center',
        slotName: 'status',
      },
      {
        title: '操作', dataIndex: 'operations', width: 160,
        align: 'center' as 'left' | 'right' | 'center',
        fixed: 'right' as 'left' | 'right',
        slotName: 'operations',
      },
    ];
  };

  const columns = ref<any>(baseColumns());
  const renderData = ref<DataState[]>([]);
  const query = ref<any>(baseQuery());
  const pagination = reactive<any>({});
  const rowSelection = reactive({
    type: 'checkbox' as const,
    selectedRowKeys: [] as any,
    // defaultSelectedRowKeys: [],
    showCheckedAll: true,
  });
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: '状态一',
      value: 1,
    },
    {
      label: '状态二',
      value: 2,
    },
  ]);

  const isReset = ref(true); // 是否重置
  // const selectionKeys = ref<any>([]);
  let selectionKeys: string[] = []; // 选中项ID
  let selectionDatas: any = []; // 选中项
  const spinLoading = ref(false);
  const spinTip = ref();
  const detailRef = ref();

  const tableTheadOptions = ref<any>({
    id: {
      label: 'Id',
      field: 'id',
    },
    name: {
      label: '名称',
      field: 'name',
    },
    created_at: {
      label: '创建时间',
      field: 'created_at',
    },
    status: {
      label: '状态',
      field: 'status',
    },
  });
  const allTableThead = ref(['name', 'created_at', 'status']);
  // 默认表头
  const defaultTableThead = ref(['name', 'created_at']);

  const stateObj: any = {
    // dialogVisible: ref(false), // 无效
    // dialogTitle: '',
    // btnLoading: false,

    isSelectAll: false,
  };

  // 分页
  const onPageChange = (page: number) => {
    isReset.value = false;
    fetchData({ ...query.value, page });
  };
  const onPageSizeChange = (limit: number) => {
    isReset.value = false;
    query.value.page = 1;
    fetchData({ ...query.value, limit });
  };
  // 列表
  const fetchData = async (
    params: QueryParams = { ...query.value }
  ) => {
    setLoading(true);
    reset();
    try {
      const { data } = await apiList(params);
      renderData.value = data.data;
      query.value.page = params.page;
      query.value.limit = params.limit;
      pagination.current = params.page;
      pagination.pageSize = params.limit;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 添加/编辑
  const add = (row?: DataState) => {
    detailRef.value.fetchData(row);
  };
  // 删除
  const del = (row: any[]) => {
    if (!row.length) {
      selectMsg();
    } else {
      let title = '删除';
      let message = `确定要删除选中的 <span style="color:red">${row.length} </span> 条数据吗？`;
      let ids = row;
      if (row.length === 1 && row[0].id) {
        title = `${title}ID：${row[0].id}`;
        message = `确定要删除 <span style="color:red">${row[0].name} </span> 这条数据吗？`;
        ids = [row[0].id];
      }
      Modal.warning({
        title,
        content: () => h(compile(message)),
        closable: true,
        hideCancel: false,
        onOk: (async () => {
          setLoading(true);
          try {
            await apiDel({ids});
          } catch (err) {
            setLoading(false);
          } finally {
            fetchData({...query.value});
            setLoading(false);
          }
        }),
      });
    }
  };
  // 重置
  const reset = async () => {
    if (isReset.value) {
      rowSelection.selectedRowKeys = [];
      selectionKeys = [];
    } else {
      isReset.value = true;
    }
  };
  // 搜索
  const search = () => {
    query.value.page = 1;
    fetchData({...query.value} as unknown as QueryParams);
  };
  // 刷新
  const refresh = () => {
    query.value = baseQuery();
    fetchData({...query.value});
  };
  // 排序
  const sorting = (dataIndex: string, direction: string) => {
    query.value.sort_field = dataIndex;
    if (direction === 'ascend') {
      query.value.sort_value = 'asc';
      fetchData({...query.value});
    }
    if (direction === 'descend') {
      query.value.sort_value = 'desc';
      fetchData({...query.value});
    }
  };

  // 点击行选择器时触发 -- table 表头 【废弃：全选时不触发】
  const select = (rowKeys: any[], rowKey: any, record: any) => {
    selectionKeys = rowKeys;
    if (!rowKeys.includes(rowKey)) {
      selectionDatas.forEach((item: any, index: string) => {
        if (index === rowKey) {
          selectionDatas.splice(index, 1);
        }
      });
    } else {
      selectionDatas[rowKey] = record;
    }
  };
  // 已选择的数据行发生改变时触发 -- table 表头
  const selectionChange = (rowKeys: any[]) => {
    rowSelection.selectedRowKeys = rowKeys;
    selectionKeys = rowKeys;
    selectionDatas = [];
    renderData.value.forEach((record: any, index: number) => {
      const rowKey = record.id;
      if (rowKeys.includes(rowKey) && !selectionDatas[rowKey]) {
        selectionDatas[rowKey] = record;
      }
    });
  };
  // 全选操作 -- 自定义按钮
  const customSelectAll = (value: boolean | any) => {
    proxy.$refs.tableRef.selectAll(value);
  };
  const selectMsg = (message?: string) => {
    Message.info(message || '请选择需要操作的数据');
  };
  // 批量选择
  const batchSelect = (selectType?: string) => {
    console.log(selectionKeys);
    if (!selectionKeys.length) {
      selectMsg();
    } else {
      console.log(selectType);
    }
  };
  // 批量删除
  const batchDel = () => {
    del(selectionKeys);
  };
  // 导出
  const doExport = async () => {
    spinLoading.value = true;
    spinTip.value = '数据下载中，请稍候...';
    await apiExport({...query.value}).then(res => {
      spinLoading.value = false;
      const { url } = res.data;
      exportExcel(url);
    }).catch(() => {
      spinLoading.value = false;
    });
  };

  const initColumns = (tableTheads: any) => {
    // columns.value.forEach((item: any, index: number) => {
    //   if (!['id', 'operations'].includes(item.dataIndex) && (!tableTheads || !tableTheads.includes(item.dataIndex))) {
    //     columns.value.splice(index, 1);
    //   }
    // });
    const showColumns: any = [];
    baseColumns().forEach((item: any, index: number) => {
      if (['id', 'operations'].includes(item.dataIndex) || tableTheads.includes(item.dataIndex)) {
        showColumns.push(item);
      }
    });
    columns.value = showColumns;
  };
  // table 列配置
  const handleTableThead = (values: (string | number | boolean)[]) => {
    initColumns(values);
  };

  initColumns(defaultTableThead.value);
  fetchData();
</script>

<script lang="ts">
  export default {
    name: 'Test',
  };
</script>

<style scoped lang="less">
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
